// pages/2411Ayiliao-pages/physical/record.js
Page({
	data: {
		patientInfo: {
			name: '蒋峰',
			relation: '本人',
			idNumber: '622*********0909',
			patientId: null
		},
		patientList: [],
		records: [],
		filteredRecords: [],
		loading: false,
		showPatientModal: false,
		showTimePicker: false,
		startDate: '',
		endDate: '',
		currentSelecting: 'start',
		years: [2020, 2021, 2022, 2023, 2024, 2025],
		months: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'],
		days: ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31'],
		startPickerValue: [5, 9, 7],
		endPickerValue: [5, 9, 7]
	},

	onLoad() {
		this.initPatient();
		this.loadPatientList();
		this.loadRecords();
	},

	initPatient() {
		const cache = wx.getStorageSync('userInfo') || {};
		this.setData({
			patientInfo: {
				name: cache.nickName || '蒋峰',
				relation: '本人',
				idNumber: cache.phoneNumber || '622*********0909',
				patientId: cache.patientId || null
			}
		});
	},

	loadPatientList() {
		wx.request({
			url: 'http://localhost:8080/patient/list',
			method: 'GET',
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				if (res.statusCode === 200 && res.data) {
					let patientData = res.data;
					if (typeof patientData === 'string') {
						try { patientData = JSON.parse(patientData); } catch (e) { return; }
					}
					if (patientData.code !== undefined) {
						if (patientData.code !== 200) return;
						patientData = patientData.data;
					}
					if (!Array.isArray(patientData)) {
						if (patientData.data && Array.isArray(patientData.data)) patientData = patientData.data;
						else if (patientData.list && Array.isArray(patientData.list)) patientData = patientData.list;
						else if (patientData.patients && Array.isArray(patientData.patients)) patientData = patientData.patients;
						else return;
					}
					const processedData = patientData.map(patient => ({
						id: patient.id || patient.patientId,
						name: patient.name || patient.patientName || patient.realName,
						relation: patient.relationTypeName || patient.relationship || patient.relation || '本人',
						idNumber: patient.idCardNumber || patient.idCard || patient.idNumber || patient.identityCard || '622*********0909'
					}));
					this.setData({ patientList: processedData });
				}
			}
		});
	},

	loadRecords() {
		if (this.data.loading) return;
		this.setData({ loading: true });
		wx.showLoading({ title: '加载中...' });

		const params = { page: 1, pageSize: 20 };
		const pid = this.data.patientInfo.patientId;
		if (pid) { params.patientId = pid; params.patient_id = pid; }

		wx.request({
			url: 'http://localhost:8084/physical/list',
			method: 'GET',
			data: params,
			header: { 'Content-Type': 'application/json' },
			success: (res) => {
				wx.hideLoading();
				this.setData({ loading: false });

				let body = res.data;
				if (typeof body === 'string') {
					try { body = JSON.parse(body); } catch (e) { body = {}; }
				}
				if (body && body.code !== undefined) {
					if (body.code !== 200) { 
						wx.showToast({ title: body.message || '请求失败', icon: 'none' }); 
						this.setMockData();
						return; 
					}
					body = body.data;
				}
				let list = [];
				if (Array.isArray(body)) list = body; 
				else if (body && Array.isArray(body.records)) list = body.records; 
				else if (body && Array.isArray(body.list)) list = body.list; 
				else if (body && Array.isArray(body.data)) list = body.data;

				if (list.length > 0) {
					const mapped = list.map(item => ({
						id: item.id || item.orderId || Math.random().toString(36).slice(2),
						title: item.packageName || item.title || '体检套餐',
						statusText: item.statusText || item.status || '预约成功',
						doctor: item.doctorName || '医生',
						date: this.formatDate(item.appointTime || item.date || item.createTime || item.operateTime),
						amount: (item.amount != null ? Number(item.amount) : 0).toFixed(2)
					}));

					this.setData({ records: mapped, filteredRecords: mapped });
					wx.showToast({ title: '加载成功', icon: 'success' });
				} else {
					this.setMockData();
				}
			},
			fail: () => {
				wx.hideLoading();
				this.setData({ loading: false });
				this.setMockData();
			}
		});
	},

	setMockData() {
		// 本地模拟数据
		const mock = [
			{ id: 1, title: '男性体检基础A套餐', statusText: '预约成功', doctor: '王敏', date: '2020-10-05', amount: '1200.00' },
			{ id: 2, title: '男性体检基础A套餐', statusText: '已完成', doctor: '王敏', date: '2020-10-05 10:50', amount: '1200.00' }
		];
		this.setData({ records: mock, filteredRecords: mock });
		wx.showToast({ title: '暂无数据', icon: 'none' });
	},

	formatDate(ts) {
		if (!ts) return '';
		const d = new Date(ts);
		if (isNaN(d.getTime())) return ts;
		const y = d.getFullYear();
		const m = String(d.getMonth() + 1).padStart(2, '0');
		const day = String(d.getDate()).padStart(2, '0');
		const hh = String(d.getHours()).padStart(2, '0');
		const mm = String(d.getMinutes()).padStart(2, '0');
		return `${y}-${m}-${day}${(hh+mm!=='0000') ? ' ' + hh + ':' + mm : ''}`
	},

	// 切换就诊人
	switchPatient() {
		this.setData({ showPatientModal: true });
	},

	closePatientModal() {
		this.setData({ showPatientModal: false });
	},

	selectPatient(e) {
		const patient = e.currentTarget.dataset.patient;
		this.setData({
			patientInfo: {
				name: patient.name,
				relation: patient.relation,
				idNumber: patient.idNumber,
				patientId: patient.id
			},
			showPatientModal: false
		});
		// 重新加载该患者的预约记录
		this.loadRecords();
	},

	stopPropagation() {
		// 阻止事件冒泡
	},

	// 时间筛选
	selectTimeRange(e) {
		const range = e.currentTarget.dataset.range;
		if (range === 'year') {
			// 显示近一年的记录
			const currentYear = new Date().getFullYear();
			this.filterRecordsByYear(currentYear);
		}
	},

	showTimePicker() {
		this.setData({ showTimePicker: true });
	},

	closeTimePicker() {
		this.setData({ showTimePicker: false });
	},

	selectStartDate() {
		this.setData({ currentSelecting: 'start' });
	},

	selectEndDate() {
		this.setData({ currentSelecting: 'end' });
	},

	onPickerChange(e) {
		const value = e.detail.value;
		const year = this.data.years[value[0]];
		const month = this.data.months[value[1]];
		const day = this.data.days[value[2]];
		
		if (this.data.currentSelecting === 'start') {
			this.setData({
				startDate: `${year}年${month}月${day}日`,
				startPickerValue: value
			});
		} else {
			this.setData({
				endDate: `${year}年${month}月${day}日`,
				endPickerValue: value
			});
		}
	},

	confirmTimeRange() {
		this.filterRecordsByDateRange();
		this.setData({ showTimePicker: false });
	},

	filterRecordsByYear(year) {
		const filteredList = this.data.records.filter(item => {
			const itemYear = new Date(item.date).getFullYear();
			return itemYear === year;
		});
		this.setData({ filteredRecords: filteredList });
	},

	filterRecordsByDateRange() {
		const startDate = new Date(this.data.startDate.replace(/年|月|日/g, '-'));
		const endDate = new Date(this.data.endDate.replace(/年|月|日/g, '-'));
		
		const filteredList = this.data.records.filter(item => {
			const itemDate = new Date(item.date);
			return itemDate >= startDate && itemDate <= endDate;
		});
		
		this.setData({ filteredRecords: filteredList });
	},

	toDetail(e) {
		const item = e.currentTarget.dataset.item;
		wx.navigateTo({ url: `/pages/2411Ayiliao-pages/physical/detail?id=${item.id}` });
	},

	toReport(e) {
		const item = e.currentTarget.dataset.item;
		wx.navigateTo({ url: `/pages/2411Ayiliao-pages/physical/report?id=${item.id}` });
	}
});